package top.frsf.mqtt.config;

import io.netty.handler.codec.mqtt.MqttMessageType;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Configuration;
import top.frsf.mqtt.handler.strategy.abs.MqttMessageHandlerStrategy;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * MQTT协议事件Handler上下文
 *
 * @author He Kuntao
 * @since 2025/5/29 14:11
 */
@Configuration
public class MqttHandlerContext implements ApplicationContextAware {

    /**
     * MQTT事件处理器 MAP
     */
    private final Map<MqttMessageType, MqttMessageHandlerStrategy> strategyMap = new ConcurrentHashMap<>();

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        // 获取所有MqttMessageHandlerStrategy的实现类
        Map<String, MqttMessageHandlerStrategy> beans = applicationContext.getBeansOfType(MqttMessageHandlerStrategy.class);
        // 遍历添加
        for (MqttMessageHandlerStrategy strategy : beans.values()) {
            MqttMessageType type = strategy.supportedType();
            strategyMap.put(type, strategy);
        }
    }

    /**
     * 获取处理器
     *
     * @param type MQTT事件类型
     * @return 处理器
     */
    public MqttMessageHandlerStrategy getStrategy(MqttMessageType type) {
        MqttMessageHandlerStrategy handlerStrategy = strategyMap.get(type);
        if (handlerStrategy == null) {
            throw new RuntimeException("未找到处理器");
        }
        return handlerStrategy;
    }
}
